package com.demo.netty.demo01.handler;

import com.demo.netty.demo01.po.Cat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class CatServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务端处理(channelRead)线程为：" + Thread.currentThread().getName());
        //有一个非常耗时的任务：
        //  提交到该Channel对应的taskQueue中就可以了
        ctx.channel().eventLoop().execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            System.out.println("服务端处理(channelRead-innerTask)线程为：" + Thread.currentThread().getName());
            if (msg instanceof ByteBuf) {
                ByteBuf buf = (ByteBuf) msg;
                System.out.println("接收到客户端消息：" + buf.toString(StandardCharsets.UTF_8));
                ctx.writeAndFlush(Unpooled.copiedBuffer("你好客户端：我是服务端，喵喵喵！！！2\r\n".getBytes(StandardCharsets.UTF_8)));
            }
        });
        ctx.channel().eventLoop().schedule(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            System.out.println("服务端处理(channelRead-innerTask)线程为：" + Thread.currentThread().getName());
            if (msg instanceof ByteBuf) {
                ByteBuf buf = (ByteBuf) msg;
                System.out.println("接收到客户端消息：" + buf.toString(StandardCharsets.UTF_8));
                ctx.writeAndFlush(Unpooled.copiedBuffer("你好客户端：我是服务端，喵喵喵！！！scheduel\r\n".getBytes(StandardCharsets.UTF_8)));
            }
        }, 5, TimeUnit.SECONDS);
        System.out.println("go no....");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("你好客户端：我是服务端，喵喵喵！！！1\r\n".getBytes(StandardCharsets.UTF_8)));
    }
}
